<template>
  <el-form :model="formData" ref="formRef" label-width="100px">
    <template v-for="field in fields" :key="field.name">
      <el-form-item :label="field.label" :prop="field.name">
        <!-- 输入框 -->
        <el-input v-if="field.type === 'input'" v-model="formData[field.name]" :placeholder="field.placeholder || ''" :type="field.inputType || 'text'" clearable />

        <!-- 下拉框 -->
        <el-select v-else-if="field.type === 'select'" v-model="formData[field.name]" :placeholder="field.placeholder || '请选择'" clearable>
          <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>

        <!-- 单选框 -->
        <el-radio-group v-else-if="field.type === 'radio'" v-model="formData[field.name]">
          <el-radio v-for="option in field.options" :key="option.value" :label="option.value">
            {{ option.label }}
          </el-radio>
        </el-radio-group>

        <!-- 多选框 -->
        <el-checkbox-group v-else-if="field.type === 'checkbox'" v-model="formData[field.name]">
          <el-checkbox v-for="option in field.options" :key="option.value" :label="option.value">
            {{ option.label }}
          </el-checkbox>
        </el-checkbox-group>

        <!-- 文本域 -->
        <el-input v-else-if="field.type === 'textarea'" type="textarea" v-model="formData[field.name]" :placeholder="field.placeholder || ''" :rows="field.rows || 3" clearable />

        <!-- 时间日期选择框 -->
        <el-date-picker v-else-if="field.type === 'datetime'" v-model="formData[field.name]" type="datetime" :placeholder="field.placeholder || '请选择日期时间'" style="width: 100%;" clearable />
      </el-form-item>
    </template>

    <el-form-item>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, toRefs, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  fields: {
    type: Array,
    required: true
  },
  onSave: Function,
  onCancel: Function,
  rules: Object // 可选，校验规则
})

const formRef = ref(null)

// 初始化表单数据
const formData = reactive({})
props.fields.forEach(field => {
  if (field.type === 'checkbox') {
    formData[field.name] = field.defaultValue || []
  } else {
    formData[field.name] = field.defaultValue ?? ''
  }
})

// 监听fields变化，动态更新formData（可选）
watch(
  () => props.fields,
  newFields => {
    newFields.forEach(field => {
      if (!(field.name in formData)) {
        if (field.type === 'checkbox') {
          formData[field.name] = field.defaultValue || []
        } else {
          formData[field.name] = field.defaultValue ?? ''
        }
      }
    })
  },
  { deep: true }
)

function handleCancel() {
  if (props.onCancel) {
    props.onCancel()
  } else {
    // 默认清空表单
    Object.keys(formData).forEach(key => {
      if (Array.isArray(formData[key])) {
        formData[key] = []
      } else {
        formData[key] = ''
      }
    })
    ElMessage.info('已重置表单')
  }
}

function handleSave() {
  if (formRef.value) {
    formRef.value.validate(valid => {
      if (valid) {
        if (props.onSave) {
          props.onSave({ ...formData })
        } else {
          ElMessage.success('保存成功')
          console.log('保存数据:', formData)
        }
      } else {
        ElMessage.error('请检查表单填写项')
      }
    })
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
</style>
